var express = require('express');
var router = express.Router();
var async = require('async');
var substationManageController = require('../controllers/substation_manage');

//mongodb数据库链接
const mongo = require('mongodb');
const MongoClient = require('mongodb').MongoClient
const mongoConfig = require('../config/mongodb');
var url = 'mongodb://' + mongoConfig.user + ':' + mongoConfig.password + '@' + mongoConfig.host + ':' + mongoConfig.port + '/' + mongoConfig.database + '?authMechanism=' + mongoConfig.authMechanism + '&authSource=' + mongoConfig.authSource;

//bson中间件引用
const BSON = require('bson');
const Long = BSON.Long;

//查询变电站
router.post('/search', function(req, res) {
    var param = req.body;
    let requirement = param.requirement;
    let lastRequirement = {}; //定义一个新对象
    for (let i in requirement) {
        let item = requirement[i];
        if (item != "" && i == 'crtime') {
            //把日期转换成时间戳
            let newCrtime = new Date(item).getTime() / 1000;
            lastRequirement[i] = newCrtime
            continue; //进入下次循环
        } else if (item != "") {
            //把非空数据添加到新对象中
            lastRequirement[i] = item;
        }
    }
    param.requirement = lastRequirement;
    try {
        async.auto({
            list: function(cb) {
                substationManageController.pageList(param, cb);
            },
            listLength: function(cb) {
                substationManageController.count(param, cb);
            }
        }, function(err, data) {
            res.send({
                code: "200",
                msg: "获取详情成功",
                result: data.list,
                total: data.listLength
            });
        });
    } catch (err) {
        res.end(err.stack);
    }
});

//根据省市区的区代码查询变电站
router.post('/distSearchSubstation', function(req, res) {
    try {
        let paramVal = parseInt(req.body.dist_code);
        let param = {
            'dist_code': paramVal
        };
        async.auto({
            search: function(cb) {
                substationManageController.getList(param, cb);
            }
        }, function(err, data) {
            let list = [];
            let search = data.search;
            search.forEach(function(item) {
                let obj = {};
                obj.label = item.full;
                obj.value = item.sid.toString();
                list.push(obj);
            });

            if (data) {
                res.send({
                    code: "200",
                    msg: "获取详情成功",
                    result: list
                });
            } else {
                res.send({
                    code: 404,
                    msg: "变电站查询失败",
                    result: list
                });
            }
        });
    } catch (err) {
        res.end(err.stack);
    }
});

//新增变电站
router.post('/add', function(req, res) {
    try {
        var body = req.body;
        for (let i in body) {
            if (i == 'sid') {
                // console.log('777',Long.fromString(body[i]))
                body[i] = parseInt(body[i]);
                // console.log('666',Long.fromString(body[i]))
            } //把sid的值转成整型
            if (i == 'prov_code') {
                body[i] = Number(body[i]);
            } //把prov_code的值转成数值
            if (i == 'city_code') {
                body[i] = Number(body[i]);
            } //把crtime的值转成整型
            if (i == 'dist_code') {
                body[i] = Number(body[i]);
            } //把crtime的值转成整型
            if (i == 'longitude') {
                body[i] = parseFloat(body[i]);
            } //把longitude的值转成浮点数
            if (i == 'latitude') {
                body[i] = parseFloat(body[i]);
            } //把latitude的值转成浮点数

            if (i == 'crtime') {
                body[i] = parseInt(body[i]);
            } //把crtime的值转成整型
            if (i == 'chtime') {
                body[i] = parseInt(body[i]);
            } //把chtime的值转成整型
            if (i == 'status') {
                body[i] = parseInt(body[i]);
            } //把status的值转成整型
            if (i == 'voltage') {
                body[i] = parseInt(body[i]);
            } //把voltage的值转成整型
        }
        // console.log('body',body);
        //获取id
        let param = {
            sid: body.sid
        }
        //获取当前区代码
        let provCitydistCode = {
            "dist_code": body.dist_code
        };
        // console.log('provCitydistCode', provCitydistCode);
        //设置当前变电站sid
        let sid = null;
        //流程管控
        async.auto({
            verifyId: function(cb) {
                substationManageController.getOne(param, function(err, data) {
                    // console.log('1', data)
                    if (data) {
                        cb({
                            code: 404,
                            msg: "变电站ID已存在",
                            result: data
                        });
                    } else {
                        cb(null);
                    }
                });
            },
            getProvCityDistTotal: function(cb) {
                substationManageController.getList(provCitydistCode, function(err, data) {
                    let partNum = Math.floor(Math.random() * 90 + 10); //获取二位随机数
                    if (data.length >= 0 && data.length < 9) {
                        body.sid = new BSON.Long.fromNumber(body.dist_code.toString() + partNum.toString() + '0' + (data.length + 1).toString());
                        // body.sid = new BSON.Long.fromNumber(37010500103);//测试11位数据
                    } else {
                        body.sid = new BSON.Long.fromNumber(body.dist_code.toString() + partNum.toString() + (data.length + 1).toString());
                        // body.sid = new BSON.Long.fromNumber(37010500103);//测试11位数据
                    } //获取最后两位数值
                })
            },
            save: ['verifyId', function(data, cb) {
                // console.log('99999999', data);
                if (!data.verifyId) {
                    // mongodb存储数据
                    MongoClient.connect(url, function(err, db) {
                        db.collection('stationcoll').insertOne(body, function(err, docs) {
                            // console.log(docs);
                            if (docs.insertedCount == 1) {
                                cb({
                                    code: "200",
                                    msg: "添加变电站成功"
                                })
                            } else {
                                cb({
                                    code: "404",
                                    msg: "添加变电站失败"
                                })
                            }
                            db.close();
                        });
                    });
                } else {
                    cb({
                        code: "404",
                        msg: "变电站ID已经存在",
                        result: data
                    });
                }
            }]
        }, function(err, data) {
            res.send(err);
        });
    } catch (err) {
        res.end(err.stack);
    }
});

//查看变电站详情
router.post('/detail', function(req, res) {
    try {
        let obj = {};
        obj.sid = Number(req.body.sid);
        async.auto({
            detail: function(cb) {
                substationManageController.getOne(obj, function(err, data) {
                    if (data) {
                        cb({
                            code: 200,
                            msg: "变电站详情获取成功",
                            result: data
                        });
                    } else {
                        cb({
                            code: 404,
                            msg: "变电站详情获取失败"
                        });
                    }
                });
            }
        }, function(err, data) {
            res.send(err);
        });

    } catch (err) {
        res.end(err.stack);
    }
});

module.exports = router;